package com.zh.kotlin_mvvm.ui

import android.os.Bundle
import com.zh.common.base.BaseActivity
import com.zh.common.ktx.clickSingleListener
import com.zh.common.ktx.toast
import com.zh.kotlin_mvvm.databinding.ActivityTtsBinding
import com.zh.common.utils.TtsUtils
import com.zh.kotlin_mvvm.voice.MediaManager

class TtsActivity : BaseActivity<ActivityTtsBinding>() {

    private var filePath = ""

    override fun initView(savedInstanceState: Bundle?) {
        TtsUtils.instance.launcherActivity(this) {
            if (it) "TTS初始化成功".toast() else "TTS初始化失败".toast()
        }
        viewBinding.apply {
            val content = content.text.toString()
            init.clickSingleListener {
                TtsUtils.instance.checkTTSEngineAndInit()
            }
            speak.clickSingleListener {
                TtsUtils.instance.speak(content)
            }
            stop.clickSingleListener {
                TtsUtils.instance.stop()
            }
            changeFile.clickSingleListener {
                TtsUtils.instance.synthesizeTextToFile(content) {
                    "文字转换成功".toast()
                    filePath = it
                }
            }
            speakFile.clickSingleListener {
                if (filePath.isNullOrEmpty()) return@clickSingleListener
                MediaManager.playSound(this@TtsActivity, filePath) {
                    "文件播放完成".toast()
                }
            }
            TtsUtils.instance.listener { loadEnum, playEnum ->
                when (playEnum) {
                    TtsUtils.PlayEnum.PLAY_START -> {
                        "开始播放".toast()
                    }

                    TtsUtils.PlayEnum.PLAY_DONE -> {
                        "播放完成".toast()
                    }

                    TtsUtils.PlayEnum.PLAY_ERROR -> {
                        "播放错误".toast()
                    }
                }
                if (loadEnum != null && loadEnum == TtsUtils.LoadEnum.LOADED) {
                    "文字转换成功".toast()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        TtsUtils.instance.release()
        MediaManager.release()
    }

}